package com.flyco.modules.quartz.service.impl;

import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.flyco.common.constant.CommonConstant;
import com.flyco.common.exception.FlycoException;
import com.flyco.common.util.BizUtil;
import com.flyco.common.util.RestUtil;
import com.flyco.modules.quartz.constant.QuartzConstant;
import com.flyco.modules.quartz.entity.QuartzJob;
import com.flyco.modules.quartz.mapper.QuartzJobMapper;
import com.flyco.modules.quartz.service.IQuartzJobService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 定时任务在线管理
 * @Version: V1.1
 */
@Slf4j
@Service
public class QuartzJobServiceImpl extends ServiceImpl<QuartzJobMapper, QuartzJob> implements IQuartzJobService {
	@Autowired
	private QuartzJobMapper quartzJobMapper;
	@Override
	public List<QuartzJob> findByJobClassName(String jobClassName) {
		return quartzJobMapper.findByJobClassName(jobClassName);
	}


	private JSONObject createQuartz(QuartzJob quartzJob) {
		JSONObject quartzObj = new JSONObject();
		quartzObj.put("jobClassName",quartzJob.getJobClassName().trim());
		quartzObj.put("cronExpression",quartzJob.getCronExpression().trim());
		if (!StringUtils.isEmpty(quartzJob.getParameter())){
			quartzJob.setParameter(quartzJob.getParameter().trim());
		}
		quartzObj.put("parameter",quartzJob.getParameter());
		return quartzObj;
	}

	private boolean executeTask(QuartzJob quartzJob, String action) {
		StringBuilder url = new StringBuilder();
		url.append(BizUtil.getServerUrl());
		url.append("quartzJob/");
		url.append(action);
		JSONObject result = RestUtil.post(url.toString(),createQuartz(quartzJob));
		return true;
	}

	/**
	 * 保存&启动定时任务
	 */
	@Override
	public boolean saveAndScheduleJob(QuartzJob quartzJob) {
		if (CommonConstant.STATUS_NORMAL.equals(quartzJob.getStatus())) {
			// 定时器添加
			executeTask(quartzJob, QuartzConstant.SERVER_QUARTZ_ADD);

			//this.schedulerAdd(quartzJob.getJobClassName().trim(), quartzJob.getCronExpression().trim(), quartzJob.getParameter());
		}
		// DB设置修改
		quartzJob.setDelFlag(CommonConstant.DEL_FLAG_0);
		return this.save(quartzJob);
	}

	/**
	 * 恢复定时任务
	 */
	@Override
	public boolean resumeJob(QuartzJob quartzJob) {
		//schedulerDelete(quartzJob.getJobClassName().trim());
		//schedulerAdd(quartzJob.getJobClassName().trim(), quartzJob.getCronExpression().trim(), quartzJob.getParameter());

		executeTask(quartzJob, QuartzConstant.SERVER_QUARTZ_RESUME);

		quartzJob.setStatus(CommonConstant.STATUS_NORMAL);
		return this.updateById(quartzJob);
	}

	/**
	 * 暂停定时任务
	 */
	@Override
	public boolean pauseJob(QuartzJob quartzJob) {
		//schedulerDelete(quartzJob.getJobClassName().trim());
		//schedulerAdd(quartzJob.getJobClassName().trim(), quartzJob.getCronExpression().trim(), quartzJob.getParameter());

		executeTask(quartzJob, QuartzConstant.SERVER_QUARTZ_PAUSE);

		quartzJob.setStatus(CommonConstant.STATUS_DISABLE);
		return this.updateById(quartzJob);
	}

	/**
	 * 编辑&启停定时任务
	 */
	@Override
	public boolean editAndScheduleJob(QuartzJob quartzJob) {
		if (CommonConstant.STATUS_NORMAL.equals(quartzJob.getStatus())) {
			executeTask(quartzJob, QuartzConstant.SERVER_QUARTZ_RESUME);
			//schedulerDelete(quartzJob.getJobClassName().trim());
			//schedulerAdd(quartzJob.getJobClassName().trim(), quartzJob.getCronExpression().trim(), quartzJob.getParameter());
		}else{
			executeTask(quartzJob, QuartzConstant.SERVER_QUARTZ_PAUSE);
			//scheduler.pauseJob(JobKey.jobKey(quartzJob.getJobClassName().trim()));
		}
		return this.updateById(quartzJob);
	}

	/**
	 * 删除&停止删除定时任务
	 */
	@Override
	public boolean deleteAndStopJob(QuartzJob job) {
		executeTask(job, QuartzConstant.SERVER_QUARTZ_DELETE);
		//schedulerDelete(job.getJobClassName().trim());
		boolean ok = this.removeById(job.getId());
		return ok;
	}

	/**
	 * 添加定时任务
	 * 
	 * @param jobClassName
	 * @param cronExpression
	 * @param parameter
	 */
	/*private void schedulerAdd(String jobClassName, String cronExpression, String parameter) {
		try {
			// 启动调度器
			scheduler.start();

			// 构建job信息
			JobDetail jobDetail = JobBuilder.newJob(getClass(jobClassName).getClass()).withIdentity(jobClassName).usingJobData("parameter", parameter).build();

			// 表达式调度构建器(即任务执行的时间)
			CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);

			// 按新的cronExpression表达式构建一个新的trigger
			CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobClassName).withSchedule(scheduleBuilder).build();

			scheduler.scheduleJob(jobDetail, trigger);
		} catch (SchedulerException e) {
			throw new FlycoException("创建定时任务失败", e);
		} catch (RuntimeException e) {
			throw new FlycoException(e.getMessage(), e);
		}catch (Exception e) {
			throw new FlycoException("后台找不到该类名：" + jobClassName, e);
		}
	}*/

	/**
	 * 删除定时任务
	 * 
	 * @param jobClassName
	 */
/*	private void schedulerDelete(String jobClassName) {
		try {
			scheduler.pauseTrigger(TriggerKey.triggerKey(jobClassName));
			scheduler.unscheduleJob(TriggerKey.triggerKey(jobClassName));
			scheduler.deleteJob(JobKey.jobKey(jobClassName));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new FlycoException("删除定时任务失败");
		}
	}

	private static Job getClass(String classname) throws Exception {
		Class<?> class1 = Class.forName(classname);
		return (Job) class1.newInstance();
	}*/

}
